
import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'binding_terminal/widgets/binding_terminal_auto_switch_dialog.dart';

///设置定时开关机页面
class SetAutoOnOffPage extends StatefulWidget{
  ///路由名称
  static const String ROUTER = "SetAutoOnOffPage";
  final DateTime startDateTime;
  final DateTime endDateTime;
  final String week;
  final Function(String time, String week) onSet;

  const SetAutoOnOffPage({
    Key key,
    this.startDateTime,
    this.endDateTime,
    this.week,
    this.onSet,
  }) : super(key: key);

  @override
  _SetAutoOnOffPageState createState() => _SetAutoOnOffPageState();

  ///跳转方法
  ///返回Map
  static Future<Map<String,dynamic>> navigatorPushDialog(
      BuildContext context, DateTime startDateTime,
      DateTime endDateTime, String week, Function onSet) {
    return RouterUtils.routeForFutureResult(
      context,
      SetAutoOnOffPage(
        startDateTime:startDateTime,
        endDateTime:endDateTime,
        week:week,
        onSet:onSet,
      ),
      routeName: SetAutoOnOffPage.ROUTER,
    );
  }
}

class _SetAutoOnOffPageState extends BaseState<SetAutoOnOffPage>{

  DateTime _startDateTime;
  DateTime _endDateTime;
  List<String> _weekList;
  bool _isAlive;
  String _originTime;
  List<String> _originWeekList;
  @override
  void initState() {
    super.initState();
    final DateTime nowDateTime = DateTime.now();
    _startDateTime = widget?.startDateTime ??
        DateTime(nowDateTime.year, nowDateTime.month, nowDateTime.day,
            DEFAULT_START_HOUR);
    _endDateTime = widget?.endDateTime ??
        DateTime(nowDateTime.year, nowDateTime.month, nowDateTime.day,
            DEFAULT_END_HOUR);
    _originTime = getAutoOffTimeStr();
    _weekList = new List();
    _originWeekList = new List();
    if(StringUtils.isNotEmpty(widget?.week??"")){
      _weekList.addAll(widget.week.split(","));
    }
    _originWeekList.addAll(_weekList);
    _isAlive = false;
  }




  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomPadding: false,
      resizeToAvoidBottomInset: false,
      backgroundColor: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
      body: _toMainWidget(),
    );
  }

  @override
  void dispose() {
    super.dispose();
  }

  _judgeAlive(){
    String time = getAutoOffTimeStr();
    setState(() {
      _isAlive = (time != _originTime || _originWeekList.toString() != _weekList.toString());
    });
  }

  Widget _toMainWidget(){
    return Column(
      children: [
        _toTopBarWidget(),
        _toTimeWidget(),
        SizedBox(height: 10,),
        _toRepeatWidget(),
        SizedBox(height: 30,),
        _toConfirmWidget(),
      ],
    );
  }

  Widget _toTopBarWidget() {
    return VgTopBarWidget(
      title: "定时开关机",
      backgroundColor: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
      isShowBack: true,
      rightWidget: GestureDetector(
        onTap: ()async{
          bool result =
          await CommonConfirmCancelDialog.navigatorPushDialog(context,
            title: "提示",
            content: "确定关闭定时开关机功能？",
            cancelText: "取消",
            confirmText: "关闭",
            confirmBgColor: ThemeRepository.getInstance()
                .getMinorRedColor_F95355(),);
          if (result ?? false) {
            RouterUtils.pop(context);
            widget?.onSet?.call("", "");
          }
        },
        child: Container(
          padding: EdgeInsets.only(left: 15),
          height: 44,
          alignment: Alignment.center,
          child: Text(
            "关闭功能",
            style: TextStyle(
                fontSize: 14,
                height: 1.2,
                color: ThemeRepository.getInstance().getMinorRedColor_F95355()
            ),
          ),
        ),
      ),
    );
  }

  Widget _toTimeWidget(){
    return Container(
      color: ThemeRepository.getInstance().getCardBgColor_21263C(),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            padding: EdgeInsets.only(left: 15),
            alignment: Alignment.centerLeft,
            height: 43,
            child: Text(
              "时间",
              style: TextStyle(
                  fontSize: 14,
                  height: 1.2,
                  color: ThemeRepository.getInstance().getTextMinorGreyColor_808388()
              ),
            ),
          ),
          Container(
            height: 188,
            child: _toTimeChooseWidget(),
          ),
        ],
      ),
    );
  }

  ///时间选择
  Widget _toTimeChooseWidget() {
    return CupertinoTheme(
      data: CupertinoThemeData(
          textTheme: CupertinoTextThemeData(
              dateTimePickerTextStyle: TextStyle(color: Colors.white))),
      child: Row(
        children: <Widget>[
          Expanded(
            child: CupertinoDatePicker(
              mode: CupertinoDatePickerMode.time,
              use24hFormat: true,
              initialDateTime: _startDateTime,
              onDateTimeChanged: (DateTime newStartDateTime) {
                _startDateTime = newStartDateTime;
                _judgeAlive();
              },
            ),
          ),
          Text(
            "至",
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(color: Colors.white, fontSize: 18, height: 1.2),
          ),
          Expanded(
            child: CupertinoDatePicker(
              mode: CupertinoDatePickerMode.time,
              use24hFormat: true,
              initialDateTime: _endDateTime,
              onDateTimeChanged: (DateTime newEndDateTime) {
                _endDateTime = newEndDateTime;
                _judgeAlive();
              },
            ),
          ),
        ],
      ),
    );
  }

  ///重复周期
  Widget _toRepeatWidget(){
    return Container(
      color: ThemeRepository.getInstance().getCardBgColor_21263C(),
      child: Column(
        children: [
          Container(
            alignment: Alignment.centerLeft,
            padding: EdgeInsets.only(left: 15),
            height: 43,
            child: Text(
              "重复",
              style: TextStyle(
                  fontSize: 14,
                  height: 1.2,
                  color: ThemeRepository.getInstance().getTextMinorGreyColor_808388()
              ),
            ),
          ),
          _toRepeatGridWidget(),
          SizedBox(height: 12,),
        ],
      ),
    );
  }

  Widget _toRepeatGridWidget(){
    return GridView.builder(
        itemCount: 7,
        padding: EdgeInsets.only(top: 0),
        physics: BouncingScrollPhysics(),
        shrinkWrap: true,
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 4,
            mainAxisSpacing: 0,
            crossAxisSpacing: 0,
            childAspectRatio: (ScreenUtils.screenW(context)/4)/50
        ),
        itemBuilder: (BuildContext context, int index) {
          return _toGridItemWidget(context, index);
        });
  }

  Widget _toGridItemWidget(BuildContext context, int index){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        String value = (index+1).toString();
        if(_weekList.contains(value)){
          _weekList.remove((index+1).toString());
        }else{
          _weekList.add(value);
        }
        _weekList.sort((left, right){
          return int.parse(left).compareTo(int.parse(right));
        });
        _judgeAlive();
      },
      child: Container(
        alignment: Alignment.center,
        width: ScreenUtils.screenW(context)/4,
        padding: EdgeInsets.only(left: 15),
        child:
        Row(
          children: [
            Image.asset(
              _weekList.contains((index+1).toString())?
              "images/icon_repeat_checked.png":"images/icon_repeat_unchecked.png",
              width: 19,
              height: 19,
            ),
            SizedBox(width: 8,),
            Text(
              getText(index),
              style: TextStyle(
                  fontSize: 14,
                  color: ThemeRepository.getInstance().getTextColor_D0E0F7(),
                  height: 1.2
              ),
            )
          ],
        ),
      ),
    );
  }

  String getText(int index){
    switch (index){
      case 0:
        return "周一";
      case 1:
        return "周二";
      case 2:
        return "周三";
      case 3:
        return "周四";
      case 4:
        return "周五";
      case 5:
        return "周六";
      case 6:
        return "周日";
    }
  }

  _toConfirmWidget() {
    return CommonFixedHeightConfirmButtonWidget(
      onTap: (){
        if(!_isAlive){
          return;
        }
        RouterUtils.pop(context);
        String week = _weekList.toString().replaceAll("[", "").replaceAll("]", "").replaceAll(" ", "");
        if(StringUtils.isNotEmpty(week)){
          widget?.onSet?.call(getAutoOffTimeStr(), week);
        }else{
          widget?.onSet?.call("", "");
        }
      },
      isAlive: _isAlive??false,
      height: 40,
      padding: EdgeInsets.symmetric(horizontal: 15),
      selectedBgColor:
      ThemeRepository.getInstance().getPrimaryColor_1890FF(),
      unSelectBgColor:
      ThemeRepository.getInstance().getLineColor_3A3F50(),
      selectedTextStyle: TextStyle(
        color: Colors.white, fontSize: 15,),
      unSelectTextStyle: TextStyle(
        color: ThemeRepository.getInstance().getHintGreenColor_5E687C(), fontSize: 15,),
      text: "保存",
      textSize: 15,
    );

  }
  String getAutoOffTimeStr(){
    if(_startDateTime == null || _endDateTime == null){
      return null;
    }
    return "${_startDateTime.hour}:${VgToolUtils.twoDigits(_startDateTime.minute)}"
        "-"
        "${_endDateTime.hour}:${VgToolUtils.twoDigits(_endDateTime.minute)}";
  }
}

